package com.ybdz.scanner.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.ybdz.scanner.R;
import com.ybdz.scanner.api.ApiStore;
import com.ybdz.scanner.api.Constant;
import com.ybdz.scanner.base.BaseActivity;
import com.ybdz.scanner.bean.InputBean;
import com.ybdz.scanner.event.ObjEvent;
import com.ybdz.scanner.receiver.ScannerInterface;
import com.ybdz.scanner.utils.ListUtil;
import com.ybdz.scanner.utils.MyApplication;
import com.ybdz.scanner.utils.MyToast;
import com.ybdz.scanner.utils.UIUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ClassName: LuKuActivity
 * @author: zhao
 * @Description: 入库界面
 * @date 2018/2/24 10:06
 */
public class LuKuActivity extends BaseActivity{

    private ScannerInterface mScannerInterface;
    private DepositResultReceiver mDepositResultReceiver;
    private boolean isContinue = false;        //连续扫描的标志

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deposit);
        ButterKnife.bind(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        mDepositResultReceiver = new DepositResultReceiver();
        mScannerInterface = initScanner(mDepositResultReceiver);
    }

    @OnClick({R.id.ll_back, R.id.home, R.id.bt_scan, R.id.bt_history})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:          //返回
                finish();
                break;
            case R.id.home:             //返回首页
                finish();
                break;
            case R.id.bt_scan:             //扫一扫
                MyApplication.setScannerClick(Constant.Deposit);
                mScannerInterface.scan_start();
                break;
            case R.id.bt_history:       //查看历史记录
                startActivity(new Intent(LuKuActivity.this,LuKuLiShiActivity.class));
                break;
        }
    }

    /**
     * 利用广播接收扫码头的扫描结果
     */
    private class DepositResultReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String scanResult = intent.getStringExtra("value");
            //如果条码长度大于0，解码成功。如果解码长度等于0，解码失败。

            if (intent.getAction() == null){
                return;
            }
            if (intent.getAction().equals(Constant.RES_ACTION)) {

                //获取扫描结果
                if (scanResult.length() > 0 && MyApplication.getScannerClick().equals("DEPOSIT")) {
                    //解码成功
                    if (scanResult.contains(Constant.Ininventoryitem)){
                        String[] split = scanResult.split("/");
                        if (split[split.length-2].equals(Constant.Ininventoryitem)){
                            String newResult = split[split.length - 1];
                                getResult(newResult);
                        }else {
                            onFail(LuKuActivity.this);
                        }
                    }else {
                        onFailTimeOut(LuKuActivity.this);
                    }


                } else {
//                    MyToast.show(LuKuActivity.this, "数据解码失败");
                }
            }
        }
    }

    /**
     * 接口回调，网络请求
     * @param result
     */
    public void getResult(String result) {
        showLoading(LuKuActivity.this);
        if (result != null){
            ApiStore.getInput(result).enqueue(new Callback<InputBean>() {
                @Override
                public void onResponse(Call<InputBean> call, Response<InputBean> response) {
                    InputBean body = response.body();
                    int code1 = response.code();
                    if (String.valueOf(code1).equals("200") ){
                        if (body != null){
                            String code = body.getCode();
                            if (code != null && code.length() > 0){
                                if (response.isSuccessful() && code.equals("00")) {
                                    hideLoading();
                                    EventBus.getDefault().postSticky(body);
                                    InputBean.DataBean data = body.getData();

                                    String inFormCode = data.getInFormCode();
                                    ListUtil.setInputFormCode(inFormCode);

                                    String id = data.getId();
                                    //id进行非空判断；
                                    EventBus.getDefault().postSticky(new ObjEvent("scanResult",id==null?"":id));
                                    startActivity(new Intent(LuKuActivity.this,LuKuDetailActivity.class));
                                }else {
                                    hideLoading();
                                    onFail(LuKuActivity.this);

                                    //避免出现重复扫描
                                    finishScanner(mDepositResultReceiver);
                                }
                            }
                        }
                    }else {
                        hideLoading();
                        MyToast.show(LuKuActivity.this,"数据异常，请稍后再试！");
                        Log.e("异常提示：",String.valueOf(code1));

                        //避免出现重复扫描
                        finishScanner(mDepositResultReceiver);
                    }


                }

                @Override
                public void onFailure(Call<InputBean> call, Throwable t) {
                    hideLoading();
                    onFailTimeOut(LuKuActivity.this);

                    //避免出现重复扫描
                    finishScanner(mDepositResultReceiver);
                }
            });
        }
    }

    /**
     * 指定139的物理按键（中间黄色按键）按下来出发扫描
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 139 && event.getRepeatCount() == 0) {
            mScannerInterface.scan_start();
            MyApplication.setScannerClick(Constant.Deposit);
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {   //按键弹起，停止扫描
        if (keyCode == 139) {
            mScannerInterface.scan_stop();
        } else if (keyCode == 140) {
            mScannerInterface.scan_stop();

            isContinue = !isContinue;
            if (isContinue) {
                mScannerInterface.continceScan(true);
            } else {
                mScannerInterface.continceScan(false);
            }
        }
        return super.onKeyUp(keyCode, event);
    }


    @Override
    protected void onPause() {
        super.onPause();
        finishScanner(mDepositResultReceiver);
    }
}
